package client;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class MyCluster {
    public static JedisCluster jedisCluster;
    //private static final String aa = "aa";
    static {
        // 添加集群的服务节点Set集合
        Set<HostAndPort> hostAndPortsSet = new HashSet<HostAndPort>();
        // 添加节点
        hostAndPortsSet.add(new HostAndPort("192.168.91.128", 7001));
        hostAndPortsSet.add(new HostAndPort("192.168.91.128", 7002));
        hostAndPortsSet.add(new HostAndPort("192.168.91.128", 7003));
        hostAndPortsSet.add(new HostAndPort("192.168.91.128", 7004));
        hostAndPortsSet.add(new HostAndPort("192.168.91.128", 7005));
        hostAndPortsSet.add(new HostAndPort("192.168.91.128", 7006));
        //hostAndPortsSet.add(new HostAndPort("192.168.91.128", 7007));
        //hostAndPortsSet.add(new HostAndPort("192.168.91.128", 7008));

        // Jedis连接池配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大空闲连接数, 默认8个
        jedisPoolConfig.setMaxIdle(100);
        // 最大连接数, 默认8个
        jedisPoolConfig.setMaxTotal(500);
        //最小空闲连接数, 默认0
        jedisPoolConfig.setMinIdle(0);
        // 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
        jedisPoolConfig.setMaxWaitMillis(9000); // 设置2秒
        //对拿到的connection进行validateObject校验
        jedisPoolConfig.setTestOnBorrow(true);
        jedisCluster = new JedisCluster(hostAndPortsSet, jedisPoolConfig);
        Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
        for (Map.Entry<String,JedisPool> entry : clusterNodes.entrySet()){

            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }

    }

    public static String get(String key){

        return jedisCluster.get(key);

    }


}
